package binary_tree.leetcode;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;

/**
 * @Author Stark
 * @Date 2022/2/24 10:17
 */
public class Num145_PostOrderNonRecursion {
    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        if(root == null){
            return list;
        }
        Deque<TreeNode> stack = new ArrayDeque<>();
        TreeNode cur = root;
        //存储已经处理完的右结点
        TreeNode prev = null;
        //cur不等于null只是为了进入循环
        while(cur != null || !stack.isEmpty()){
            while(cur != null){
                stack.push(cur);
                cur = cur.left;
            }
            cur = stack.pop();
            //右子树为空或者一直处理完右子树
            if(cur.right == null || cur.right == prev){
                list.add(cur.val);
                prev = cur;
                cur = null;
            }else{
                //右结点不为空也没有处理过,把结点又压回栈中
                stack.push(cur);
                //往右结点移动,处理右结点
                cur = cur.right;
            }
        }
        return list;
    }
}
